package models;

import play.*;
import play.db.jpa.*;

import javax.persistence.*;

import java.util.*;

/**
 * IdeaRating.java Purpose: Model
 * 
 * @version 1.0 4/25/2011
 * @author Ahmed Mahmoud
 */

@Entity
public class IdeaRating extends Model {

	@ManyToOne (cascade=CascadeType.PERSIST)
	public Idea idea;
	@ManyToOne (cascade=CascadeType.PERSIST)
	public User user;

	public int rating;

	/**
	 * 
	 * @param idea
	 *            the idea which was rated.
	 * @param user
	 *            the user who rated the idea.
	 * @param rating
	 *            the rating which was chosen by the user for this idea
	 */
	public IdeaRating(Idea idea, User user, int rating) {
		this.idea = idea;
		this.user = user;
		this.idea.addIdeaRating(this);
		this.user.addIdeaRating(this);
		this.rating = rating;
	}

	/**
	 * it takes rating as parameter and then update the rating for this record.
	 * 
	 * @param rating
	 *            the rating which the user has chosen for certain idea.
	 * @param newIdeaRating
	 *            the whole rating for the idea.
	 * @return IdeaRating, the IdeaRating object that was modified.
	 * @author Ahmed Mahmoud
	 */
	public IdeaRating updateRating(int rating, double newIdeaRating) {
		idea.updateRating(newIdeaRating); // the whole value
		this.rating = rating;
		this.save();
		return this;
	}
	
	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * 
	 */
	public boolean cascadeDelete(){
		idea.ideaRatings.remove(this);
		idea.save();
		user.ideasRatings.remove(this);
		user.save();
		this.delete();
		return true;
	}

}
